﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Logging;
using VAdvantage.Utility;
using VAdvantage.Controls;
using System.ComponentModel;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Classes;

namespace VAdvantage.Dialogs
{
    public partial class VBPartner : ChildWindow
    {


        #region "Declaration"

        private int _windowNo;
        /** The Partner				*/
        private MBPartner _partner = null;
        /** The Location			*/
        private MBPartnerLocation _pLocation = null;
        /** The User				*/
        private MUser _user = null;
        /** Read Only				*/

        //partner Relation
        X_C_BP_Relation _bprelation = null;

        private bool _readOnly = false;

        private int _line;
        private Object[] _greeting;

        /*****************************************/
        private Object[] _bpGroup;
        private Object[] _bpRelation;
        private Object[] _bpLocation;
        /*****************************************/
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(VBPartner).FullName);
        //
        private VAdvantage.Controls.VTextBox txtValue, txtName, txtName2, txtContact, txtTitle, txtPhone, txtFax, txtPhone2, txtEMail;
        private VAdvantage.Controls.VTextBoxButton txtBtnAddress;
        private VAdvantage.Controls.VComboBox cmbGreetingBP, cmbGreetingC, cmbBPGroup, cmbBPRelation, cmbBPLocation;

        private string _title = "";

        string strValue, strGreeting, strBPGroup, strBPRelation, strBPLocation, strName, strName2, strContact, strTitle, strEMail, strC_Location_ID, strPhone, strPhone2, strFax;

        BackgroundWorker worker = null;
        int C_BPartner_ID = 0;

        private string BPtype = null;
        #endregion

        public VBPartner()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }

        /// <summary>
        ///Constructor.
        /// call loadBPartner
        /// </summary>
        /// <param name="windowNo">window No</param>
        public VBPartner(int windowNo, int BPartner_ID)
            : this()
        {
            _windowNo = windowNo;

            C_BPartner_ID = BPartner_ID;
            // LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
            InitBPartner();
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="windowNo"></param>
        /// <param name="BPartner_ID"></param>
        public VBPartner(int windowNo, int BPartner_ID, string title)
            : this()
        {

            _windowNo = windowNo;

            C_BPartner_ID = BPartner_ID;
            // LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
            InitBPartner();
            BPtype = title;
            this.Title = Msg.GetMsg(title) ;
        }

        /// <summary>
        ///Dynamic Init load Data
        /// </summary>
        private void InitBPartner()
        {
            this.Cursor = Cursors.Wait;
            bool ro = false;
            IDataReader idr = null;
            worker = new BackgroundWorker();
            worker.DoWork += (sd, ed) =>
            {

                log.Config("C_BPartner_ID=" + C_BPartner_ID);
                //  New bpartner
                if (C_BPartner_ID == 0)
                {
                    _partner = null;
                    _pLocation = null;
                    _user = null;
                    _bprelation = null;
                    _bpLocation = null;
                    _bpGroup = null;
                    //return true;
                }

                _partner = new MBPartner(Envs.GetCtx(), C_BPartner_ID, null);
                if (_partner.Get_ID() != 0)
                {
                    //	Contact - Load values
                    _pLocation = _partner.GetLocation(
                        Envs.GetCtx().GetContextAsInt(_windowNo, "C_BPartner_Location_ID"));
                    _user = _partner.GetContact(
                       Envs.GetCtx().GetContextAsInt(_windowNo, "AD_User_ID"));
                }

                _title = Msg.Translate(Envs.GetCtx(), "C_BPartner_ID");

                strValue = Msg.Translate(Envs.GetCtx(), "Value");
                strGreeting = Msg.Translate(Envs.GetCtx(), "Greeting");
                /****************************************************/
                strBPGroup = Msg.Translate(Envs.GetCtx(), "BPGroup");
                strBPRelation = Msg.Translate(Envs.GetCtx(), "BPRelation");
                strBPLocation = Msg.Translate(Envs.GetCtx(), "BPLocation");
                /****************************************************/
                strName = Msg.Translate(Envs.GetCtx(), "Name");
                strName2 = Msg.Translate(Envs.GetCtx(), "Name2");
                strContact = Msg.Translate(Envs.GetCtx(), "Contact");
                strTitle = Msg.Translate(Envs.GetCtx(), "Title");
                strEMail = Msg.Translate(Envs.GetCtx(), "Email");
                strC_Location_ID = Msg.Translate(Envs.GetCtx(), "C_Location_ID");
                strPhone = Msg.Translate(Envs.GetCtx(), "Phone");
                strPhone2 = Msg.Translate(Envs.GetCtx(), "Phone2");
                strFax = Msg.Translate(Envs.GetCtx(), "Fax");


                _readOnly = !MRole.GetDefault().CanUpdate(
                    Envs.GetCtx().GetAD_Client_ID(), Envs.GetCtx().GetAD_Org_ID(),
                    MBPartner.Table_ID, 0, false);
                log.Info("R/O=" + _readOnly);

                //	Get Data
                _greeting = FillGreeting();

                /************************************/
                _bpGroup = FillBPGroup();
                _bpRelation = FillBPRelation();
                _bpLocation = FillBPLocation(0);
                /************************************/
                ro = _readOnly;
                if (!ro)
                    ro = !MRole.GetDefault().CanUpdate(
                        Envs.GetCtx().GetAD_Client_ID(), Envs.GetCtx().GetAD_Org_ID(),
                        MBPartnerLocation.Table_ID, 0, false);
                if (!ro)
                    ro = !MRole.GetDefault().CanUpdate(
                        Envs.GetCtx().GetAD_Client_ID(), Envs.GetCtx().GetAD_Org_ID(),
                        MLocation.Table_ID, 0, false);

                idr = DataBase.DB.ExecuteReader("Select C_BPartnerRelation_ID, c_bpartnerrelation_location_id from C_BP_Relation where c_bpartner_id=" + _partner.GetC_BPartner_ID());

            };
            worker.RunWorkerCompleted += (sc, ec) =>
            {
                //	Value
                txtValue = new VTextBox("Value", true, false, true, 30, 60, "", null);
                txtValue.TextChanged += new TextChangedEventHandler(ActionPerformed);
                //fValue.addActionListener(this);
                CreateLine(txtValue, strValue, true);
                //	Greeting Business Partner
                //fGreetingBP = new JComboBox(m_greeting);
                cmbGreetingBP = new VComboBox(_greeting);
                CreateLine(cmbGreetingBP, strGreeting, false);
                //	Name
                txtName = new VTextBox("Name", true, false, true, 30, 60, "", null);
                //fName.addActionListener(this);
                txtName.TextChanged += new TextChangedEventHandler(ActionPerformed);
                CreateLine(txtName, strName, true);
                //	Name2
                txtName2 = new VTextBox("Name2", false, false, true, 30, 60, "", null);
                CreateLine(txtName2, strName2, false);

                /*************************************************/
                //	BPGroup 
                cmbBPGroup = new VComboBox(_bpGroup);
                CreateLine(cmbBPGroup, "BPGroup", true);

                //	BPRelation 
                cmbBPRelation = new VComboBox(_bpRelation);
                cmbBPRelation.SelectionChanged += new SelectionChangedEventHandler(cmbBPRelation_SelectionChanged);
                CreateLine(cmbBPRelation, "BPRelation", false);
                cmbBPRelation.SelectedIndex = -1;
                //	BPLocation 
                cmbBPLocation = new VComboBox(_bpLocation);
                CreateLine(cmbBPLocation, "BPLocation", false);
                /*************************************************/

                //	Contact
                txtContact = new VTextBox("Contact", false, false, true, 30, 60, "", null);
                CreateLine(txtContact, strContact, false);
                //	Greeting Contact
                cmbGreetingC = new VComboBox(_greeting);
                CreateLine(cmbGreetingC, strGreeting, false);
                //	Title
                txtTitle = new VTextBox("Title", false, false, true, 30, 60, "", null);
                CreateLine(txtTitle, strTitle, false);
                //	Email
                txtEMail = new VTextBox("EMail", false, false, true, 30, 40, "", null);
                CreateLine(txtEMail, strEMail, false);

                //	Location

                txtBtnAddress = new VTextBoxButton("C_Location_ID", false, ro, true, Classes.DisplayType.Location, new MLocationLookup(Envs.GetCtx(), _windowNo));
                txtBtnAddress.SetIsMandatory(true);
                CreateLine(txtBtnAddress, strC_Location_ID, true);
                //	Phone
                txtPhone = new VTextBox("Phone", false, false, true, 30, 40, "", null);
                CreateLine(txtPhone, strPhone, false);
                //	Phone2
                txtPhone2 = new VTextBox("Phone2", false, false, true, 30, 40, "", null);
                CreateLine(txtPhone2, strPhone2, false);
                //	Fax
                txtFax = new VTextBox("Fax", false, false, true, 30, 40, "", null);
                CreateLine(txtFax, strFax, false);

                LoadBPartner(C_BPartner_ID, idr);
                this.Cursor = Cursors.Arrow;
                this.OKButton.IsEnabled = true;
                this.CancelButton.IsEnabled = true;
            };
            this.OKButton.IsEnabled = false;
            this.CancelButton.IsEnabled = false;
            worker.RunWorkerAsync();
        }


        /****************************************/
        /// <summary>
        ///Fill Greeting
        /// </summary>
        /// <returns>Array of Greetings</returns>
        private Object[] FillBPGroup()
        {
            String sql = "select c_bp_group_id, Name  from c_bp_group WHERE IsActive='Y' ORDER BY 2";
            sql = MRole.GetDefault().AddAccessSQL(sql, "c_bp_group", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            return DataBase.DB.GetKeyNamePairs(sql, true);
        }
        /// <summary>
        ///Fill Greeting
        /// </summary>
        /// <returns>Array of Greetings</returns>
        private Object[] FillBPRelation()
        {
            String sql = "select c_bpartner_id, Name  from c_bpartner WHERE IsActive='Y' ORDER BY 2";
            sql = MRole.GetDefault().AddAccessSQL(sql, "c_bpartner", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            return DataBase.DB.GetKeyNamePairs(sql, true);
        }
        /// <summary>
        ///Fill Greeting
        /// </summary>
        /// <returns>Array of Greetings</returns>
        private Object[] FillBPLocation(int c_bpartner_id)
        {
            String sql = "select c_bpartner_location_id, Name  from c_bpartner_location WHERE IsActive='Y' and c_bpartner_id=" + c_bpartner_id + " ORDER BY 2";
            sql = MRole.GetDefault().AddAccessSQL(sql, "c_bpartner_location", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            return DataBase.DB.GetKeyNamePairs(sql, true);
        }
        /***************************************/
        void cmbBPRelation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int c_BPartner_id = Util.GetValueOfInt(((NamePair)(cmbBPRelation.SelectedItem)).Key);
            worker = new BackgroundWorker();
            worker.DoWork += (sc, ec) =>
            {
                _bpLocation = FillBPLocation(c_BPartner_id);
            };
            worker.RunWorkerCompleted += (sc, ec) =>
            {
                try
                {

                    cmbBPLocation.Items.Clear();
                    foreach (object value in _bpLocation)
                    {
                        cmbBPLocation.Items.Add(value);
                    }
                }
                catch { }
            };
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Event Handler For Controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ActionPerformed(object sender, TextChangedEventArgs e)
        {
            if (_readOnly)
                DisposeLocal();
            //	copy value
            else if (sender.GetHashCode() == txtValue.GetHashCode())
            {
                if (txtName.Text == null || txtName.Text.Length == 0)
                    txtName.Text = txtValue.Text;
            }
            else if (sender.GetHashCode() == txtName.GetHashCode())
            {
                if (txtContact.Text == null || txtContact.Text.Length == 0)
                    txtContact.Text = txtName.Text;
            }

        }	//



        int i = 0;
        /// <summary>
        ///Create Line Add new Row in Table
        /// </summary>
        /// <param name="field">Controlparam>
        /// <param name="title">Text(label)</param>
        /// <param name="bold">is Bold Text</param>
        private void CreateLine(Control field, String title, bool bold)
        {
            i++;

            Label label = new VLabel();
            label.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            label.Content = title;
            label.Margin = new Thickness(2);
            if (bold)
            {
                label.FontWeight = FontWeights.Bold;
            }


            if ("Name".Equals(((IControl)field).GetName()))
            {
                field.Margin = new Thickness(2);
                tblMain.RowDefinitions.Add(new RowDefinition());
                Grid.SetRow(label, tblMain.RowDefinitions.Count - 1);
                Grid.SetRow(field, tblMain.RowDefinitions.Count - 1);
                Grid.SetColumn(label, 0);
                Grid.SetColumn(field, 1);
                Grid.SetColumnSpan(field, 3);
                tblMain.Children.Add(label);
                tblMain.Children.Add(field);

                i = 0;
            }

            else if (i % 2 != 0)
            {
                field.Margin = new Thickness(2);
                tblMain.RowDefinitions.Add(new RowDefinition());
                Grid.SetRow(label, tblMain.RowDefinitions.Count - 1);
                Grid.SetRow(field, tblMain.RowDefinitions.Count - 1);
                Grid.SetColumn(label, 0);
                Grid.SetColumn(field, 1);
                tblMain.Children.Add(label);
                tblMain.Children.Add(field);
            }
            else
            {
                field.Margin = new Thickness(2);
                Grid.SetRow(label, tblMain.RowDefinitions.Count - 1);
                Grid.SetRow(field, tblMain.RowDefinitions.Count - 1);
                Grid.SetColumn(label, 2);
                Grid.SetColumn(field, 3);

                tblMain.Children.Add(label);
                tblMain.Children.Add(field);
            }
            //tblMain.Controls.Add(label, 1, tblMain.RowCount - 1);
            //centerPanel.add(label, m_gbc);

            //	Field
            //m_gbc.gridx = 1;
            //m_gbc.insets = m_fieldInsets;
            //m_gbc.fill = GridBagConstraints.HORIZONTAL;
            //  tblMain.Controls.Add(field, 2, tblMain.RowCount - 1);


            //field.Dock = DockStyle.Fill;
            if (_readOnly)
                ((Controls.IControl)field).SetReadOnly(true);// setEnabled(false);

            //tblMain.RowCount++;
        }

        /// <summary>
        ///Fill Greeting
        /// </summary>
        /// <returns>Array of Greetings</returns>
        private Object[] FillGreeting()
        {
            String sql = "SELECT C_Greeting_ID, Name FROM C_Greeting WHERE IsActive='Y' ORDER BY 2";
            sql = MRole.GetDefault().AddAccessSQL(sql, "C_Greeting", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            return DataBase.DB.GetKeyNamePairs(sql, true);
        }

        /// <summary>
        ///Load BPartner
        /// </summary>
        /// <param name="C_BPartner_ID">existing BPartner or 0 for new</param>
        /// <returns>true if loaded</returns>
        public bool LoadBPartner(int C_BPartner_ID, IDataReader idr)
        {
            log.Config("C_BPartner_ID=" + C_BPartner_ID);
            ////  New bpartner
            if (C_BPartner_ID == 0)
            {
                _partner = null;
                _pLocation = null;
                _user = null;
                _bprelation = null;
                _bpLocation = null;
                _bpGroup = null;
                return true;
            }

            //_partner = new MBPartner(Env.GetCtx(), C_BPartner_ID, null);
            if (_partner.Get_ID() == 0)
            {
                Classes.ShowMessage.Error("BPartnerNotFound", null);
                this.DialogResult = false;
                return false;
            }

            //	BPartner - Load values
            txtValue.Text = _partner.GetValue() ?? "";
            cmbGreetingBP.SelectedItem = GetGreeting(_partner.GetC_Greeting_ID());
            txtName.Text = _partner.GetName() ?? "";
            txtName2.Text = _partner.GetName2() ?? "";


            if (_pLocation != null)
            {
                int location = _pLocation.GetC_Location_ID();
                txtBtnAddress.SetValue(location);
                //
                txtPhone.Text = _pLocation.GetPhone() ?? "";
                txtPhone2.Text = _pLocation.GetPhone2() ?? "";
                txtFax.Text = _pLocation.GetFax() ?? "";
            }
            //	User - Load values

            if (_user != null)
            {
                cmbGreetingC.SelectedItem = GetGreeting(_user.GetC_Greeting_ID());
                txtContact.Text = _user.GetName() ?? "";
                txtTitle.Text = _user.GetTitle() ?? "";
                txtEMail.Text = _user.GetEMail() ?? "";
                //
                txtPhone.Text = _user.GetPhone() ?? "";
                txtPhone2.Text = _user.GetPhone2() ?? "";
                txtFax.Text = _user.GetFax() ?? "";
            }

            /*************************************************/
            if (_partner.GetC_BP_Group_ID() != 0)
            {
                try
                {
                    for (int i = 0; i < cmbBPGroup.Items.Count; i++)
                    {
                        bool val = ((VAdvantage.Model.NamePair)cmbBPGroup.Items[i]).Key.Equals(_partner.GetC_BP_Group_ID());
                        if (val)
                        {
                            cmbBPGroup.SelectedIndex = i;
                            break;
                        }

                    }
                    //Load BP

                    if (idr.Read())
                    {
                        //Relation Bpartner
                        for (int i = 0; i < cmbBPRelation.Items.Count; i++)
                        {
                            bool val = ((VAdvantage.Model.NamePair)cmbBPRelation.Items[i]).Key.Equals(Util.GetValueOfInt(idr["C_BPartnerRelation_ID"]));
                            if (val)
                            {
                                cmbBPRelation.SelectedIndex = i;
                                break;
                            }

                        }
                        //Relation Location
                        for (int i = 0; i < cmbBPLocation.Items.Count; i++)
                        {
                            bool val = ((VAdvantage.Model.NamePair)cmbBPLocation.Items[i]).Key.Equals(Util.GetValueOfInt(idr["c_bpartnerrelation_location_id"]));
                            if (val)
                            {
                                cmbBPLocation.SelectedIndex = i;
                                break;
                            }
                        }
                    }
                    idr.Close();
                }
                catch
                {
                    if (idr != null)
                    {
                        idr.Close();
                        idr = null;
                    }
                }
            }
            /*************************************************/
            return true;
        }

        /// <summary>
        ///earch _greeting for key
        /// </summary>
        /// <param name="key">C_Greeting_ID</param>
        /// <returns>Greeting</returns>
        private KeyNamePair GetGreeting(int key)
        {
            for (int i = 0; i < _greeting.Length; i++)
            {
                KeyNamePair p = (KeyNamePair)_greeting[i];
                if (p.GetKey() == key)
                    return p;
            }
            return new KeyNamePair(-1, " ");
        }


        /*****************************************/

        /// <summary>
        ///earch _bpGroup for key
        /// </summary>
        /// <param name="key">C_BPGroup_ID</param>
        /// <returns>BPGroup</returns>
        private KeyNamePair GetBPGroup(int key)
        {
            for (int i = 0; i < _bpGroup.Length; i++)
            {
                KeyNamePair p = (KeyNamePair)_bpGroup[i];
                if (p.GetKey() == key)
                    return p;
            }
            return new KeyNamePair(-1, " ");
        }
        /// <summary>
        ///earch _bpLocation for key
        /// </summary>
        /// <param name="key">C_bpLocation_ID</param>
        /// <returns>bpLocation</returns>
        private KeyNamePair GetBPLocation(int key)
        {
            for (int i = 0; i < _bpLocation.Length; i++)
            {
                KeyNamePair p = (KeyNamePair)_bpLocation[i];
                if (p.GetKey() == key)
                    return p;
            }
            return new KeyNamePair(-1, " ");
        }
        /// <summary>
        ///earch _bpRelation for key
        /// </summary>
        /// <param name="key">C_bpRelation_ID</param>
        /// <returns>_bpRelation</returns>
        private KeyNamePair GetBPRelation(int key)
        {
            for (int i = 0; i < _bpRelation.Length; i++)
            {
                KeyNamePair p = (KeyNamePair)_bpRelation[i];
                if (p.GetKey() == key)
                    return p;
            }
            return new KeyNamePair(-1, " ");
        }

        /*****************************************/


        SolidColorBrush bBrush = new SolidColorBrush();

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {

            log.Config("");

            //	Check Mandatory fields
            if (txtName.Text.Trim().Equals(""))
            {
                bBrush.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                txtName.Background = bBrush;
                ShowMessage.Info("NameMandatory", true, "", "");
                return;
            }
            else
            {
                bBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                txtName.Background = bBrush;
            }
            if (txtBtnAddress.Get_ID() == 0)
            {
                txtBtnAddress.SetBackGroundColor(DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR);// ePLAF.getFieldBackground_Error());
                ShowMessage.Info("AddressMandatory", true, "", "");
                return;
            }
            else
            {
                txtBtnAddress.SetBackGroundColor(DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR);
            }

            this.Cursor = Cursors.Wait;

            //	Check Value
            String value = txtValue.GetText();
            String name = txtName.Text;
            String name2 = txtName2.Text;
            KeyNamePair greeting = (KeyNamePair)cmbGreetingBP.SelectedItem;
            int location_ID = txtBtnAddress.Get_ID();
            String phone = txtPhone.Text;
            String phone2 = txtPhone2.Text;
            String fax = txtFax.Text;
            String contact = txtContact.Text;
            String email = txtEMail.Text;
            string title = txtTitle.GetText();
            KeyNamePair greetingC = (KeyNamePair)cmbGreetingC.SelectedItem;
            KeyNamePair bpGroup = (KeyNamePair)cmbBPGroup.SelectedItem;
            KeyNamePair bpRelation = (KeyNamePair)cmbBPRelation.SelectedItem;
            KeyNamePair bpLocatiuon = (KeyNamePair)cmbBPLocation.SelectedItem;

            if (bpGroup == null)
            {
               // txtBtnAddress.SetBackGroundColor(DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR);// ePLAF.getFieldBackground_Error());
                ShowMessage.Info("BPGroupMandatory", true, "", "");
                return;
            }

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (sd, ed) =>
            {
                if (_partner == null)
                {
                    int AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
                    _partner = MBPartner.GetTemplate(Envs.GetCtx(), AD_Client_ID);
                    bool isSOTrx = Envs.GetCtx().IsSOTrx(_windowNo);
                    _partner.SetIsCustomer(isSOTrx);
                    _partner.SetIsVendor(!isSOTrx);
                    if (BPtype != null)
                    {
                        if (BPtype == "Customer")
                        {
                            _partner.SetIsCustomer(true);
                        }
                        else if (BPtype == "Employee")
                        {
                            _partner.SetIsEmployee(true);
                        }
                        else if (BPtype == "Vendor")
                        {
                            _partner.SetIsVendor(true);
                        }
                        else if (BPtype == "Prospect")
                        {
                            _partner.SetIsProspect(true);
                        }
                    }
                }

                if (value == null || value.Length == 0)
                {
                    //	get Table Documet No
                    value = MSequence.GetDocumentNo(Envs.GetCtx().GetAD_Client_ID(), "C_BPartner", null);
                    Dispatcher.BeginInvoke(() => { txtValue.Text = value; });
                }
                _partner.SetValue(value);
                //
                _partner.SetName(name);
                _partner.SetName2(name2);
                //KeyNamePair p = (KeyNamePair)cmbGreetingBP.SelectedItem;
                if (greeting != null && greeting.GetKey() > 0)
                {
                    _partner.SetC_Greeting_ID(greeting.GetKey());
                }
                else
                {
                    _partner.SetC_Greeting_ID(0);
                }
                /***************************************************/
                _partner.SetC_BP_Group_ID(Util.GetValueOfInt(bpGroup.GetKey()));
                /***************************************************/

                if (_partner.Save())
                    log.Fine("C_BPartner_ID=" + _partner.GetC_BPartner_ID());
                else
                {
                    Classes.ShowMessage.Error("SearchKeyExist", null);
                    this.Cursor = Cursors.Arrow;
                    return;
                }

                //	***** Business Partner - Location *****
                if (_pLocation == null)
                    _pLocation = new MBPartnerLocation(_partner);
                _pLocation.SetC_Location_ID(txtBtnAddress.Get_ID());
                //
                _pLocation.SetPhone(phone);
                _pLocation.SetPhone2(phone2);
                _pLocation.SetFax(fax);
                if (_pLocation.Save())
                    log.Fine("C_BPartner_Location_ID=" + _pLocation.GetC_BPartner_Location_ID());
                else
                {
                    //   ADialog.error(m_WindowNo, this, "BPartnerNotSaved", Msg.translate(Env.getCtx(), "C_BPartner_Location_ID"));
                    Classes.ShowMessage.Error("BPartnerNotSaved", null);
                    this.Cursor = Cursors.Arrow;
                    return;
                }

                //	***** Business Partner - User *****
                //String contact = txtContact.Text;
                //String email = txtEMail.Text;
                if (_user == null && (contact.Length > 0 || email.Length > 0))
                    _user = new MUser(_partner);
                if (_user != null)
                {
                    if (contact.Length == 0)
                        contact = name;
                    _user.SetName(contact);
                    _user.SetEMail(email);
                    _user.SetTitle(title);
                    // = (KeyNamePair)cmbGreetingC.SelectedItem;
                    if (greetingC != null && greetingC.GetKey() > 0)
                        _user.SetC_Greeting_ID(greetingC.GetKey());
                    else
                        _user.SetC_Greeting_ID(0);
                    //
                    _user.SetPhone(phone);
                    _user.SetPhone2(phone2);
                    _user.SetFax(fax);
                    if (_user.Save())
                    {
                        log.Fine("AD_User_ID=" + _user.GetAD_User_ID());
                    }
                    else
                    {
                        Classes.ShowMessage.Error("BPartnerNotSaved", null);
                        this.Cursor = Cursors.Arrow;
                        return;
                    }

                    /*************************************************/
                    if (bpRelation != null && bpLocatiuon != null)
                    {
                        if (bpRelation.ToString().Trim() == "" || bpLocatiuon.ToString().Trim() == "")
                        {
                            int dele = DataBase.DB.ExecuteQuery("DELETE from C_BP_Relation where c_bpartner_id=" + _partner.GetC_BPartner_ID());
                            if (dele == -1)
                            {
                                log.SaveError("C_BP_RelationNotDeleted", "c_bpartner_id=" + _partner.GetC_BPartner_ID());
                            }
                        }
                        else
                        {
                            //Business Partner Relation 
                            _bprelation = new X_C_BP_Relation(Envs.GetCtx(), 0, null);
                            _bprelation.SetAD_Client_ID(_partner.GetAD_Client_ID());
                            _bprelation.SetAD_Org_ID(_partner.GetAD_Org_ID());
                            _bprelation.SetName(_partner.GetName());
                            _bprelation.SetDescription(_partner.GetDescription());
                            _bprelation.SetC_BPartner_ID(_partner.GetC_BPartner_ID());
                            _bprelation.SetC_BPartner_Location_ID(_pLocation.GetC_BPartner_Location_ID());
                            _bprelation.SetC_BP_Relation_ID(Util.GetValueOfInt(bpRelation.GetKey()));
                            _bprelation.SetC_BPartnerRelation_ID(Util.GetValueOfInt(bpRelation.GetKey()));
                            _bprelation.SetC_BPartnerRelation_Location_ID(Util.GetValueOfInt(bpLocatiuon.GetKey()));
                            _bprelation.SetIsBillTo(true);
                            if (_bprelation.Save())
                            {
                                log.Fine("C_BP_Relation_ID=" + _bprelation.GetC_BP_Relation_ID());
                            }
                            else
                            {
                                Classes.ShowMessage.Error("BPRelationNotSaved", null);
                                this.Cursor = Cursors.Arrow;
                                return;
                            }
                        }
                    }
                    /*************************************************/

                }
            };
            bgw.RunWorkerCompleted += (sc, ec) =>
            {
                DisposeLocal();
                this.Cursor = Cursors.Arrow;
                this.DialogResult = true;
            };
            bgw.RunWorkerAsync();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DisposeLocal();
            this.DialogResult = false;
        }

        /// <summary>
        /// Dispose Local variable
        /// </summary>
        private void DisposeLocal()
        {

            _pLocation = null;
            _user = null;
            txtValue = null;
            txtName = null;
            txtName2 = null;
            txtContact = null;
            txtTitle = null;
            txtPhone = null;
            txtFax = null;
            txtPhone2 = null;
            txtEMail = null;
            txtBtnAddress = null;
            cmbGreetingBP = null;
            cmbGreetingC = null;
            _greeting = null;
            _bpGroup = null; ;
            _bpLocation = null;
            _bpRelation = null;
        }

        /// <summary>
        ///Returns BPartner ID
        /// </summary>
        /// <returns>C_BPartner_ID (0 = not saved)</returns>
        public int GetC_BPartner_ID()
        {
            if (_partner == null)
                return 0;
            return _partner.GetC_BPartner_ID();
        }
    }
}

